//
//  Contact.m
//  Speedater
//
//  Created by Ngo Thang on 12/31/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Contact.h"
#import "Start.h"
#import "ContactSearch.h"
#import "ContactDetail.h"
#import "AppDelegate.h"
#import "asyncimageview.h"
#import "JSON.h"

@interface Contact (Private)

- (void)cleanup;

@end

@implementation Contact (Private)

- (void)cleanup 
{
    self.myTabBar = nil;
    self.myTableView = nil;
    self.findContactButton = nil;
    self.listOfSections = nil;
}

@end


@implementation Contact

@synthesize myTabBar;
@synthesize myTableView;
@synthesize findContactButton;
@synthesize listOfSections;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"CONTACT -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (IBAction)findContactButtonClick:(id)sender
{
    ContactSearch *contactSearch = [[ContactSearch alloc] init];
    [self.navigationController pushViewController:contactSearch animated:YES];
    [contactSearch release];
}

- (void)loadContacts 
{
    NSString *postString = [NSString stringWithFormat:@"op=loadMerkListe&username=%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];       
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
    
}

- (void)goStart
{
    // goto Start form
    self.tabBarController.selectedIndex = 0;
    
    UINavigationController *nav1 = [self.tabBarController.viewControllers objectAtIndex:0];
    for (UIViewController *vc in nav1.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"CONTACT -> popToViewController: %@", vc);
            [nav1.topViewController.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"tab_isBack"];
    self.tabBarController.selectedIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"tab_two"]==2 ? 0 : [[NSUserDefaults standardUserDefaults] integerForKey:@"tab_two"];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"CONTACT -> viewDidLoad");
    [super viewDidLoad];
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // navigation title
    self.title = @"Merkliste";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // set color for tableviewcells line
    myTableView.separatorColor = [UIColor colorWithRed:204 green:204 blue:204 alpha:0.2];
    
    // selected tab
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:1]];
    
    // init data
    listOfSections = [[NSMutableArray alloc] init]; 
}

- (void)viewDidUnload
{
    //NSLog(@"CONTACT -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"CONTACT -> viewWillAppear");
    //NSLog(@"CONTACT -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:2 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
    
    // update contact list
    [self loadContacts];
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark - TableView Delege

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [listOfSections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[listOfSections objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];        
    }
    else 
    {
        [[cell viewWithTag:999] removeFromSuperview];
        [[cell viewWithTag:998] removeFromSuperview];
        [[cell viewWithTag:997] removeFromSuperview];
        [[cell viewWithTag:996] removeFromSuperview];
    }
    // Configure the cell.
    NSMutableArray *sectionFields = [listOfSections objectAtIndex:[indexPath section]];
    NSDictionary *dicField = [sectionFields objectAtIndex:[indexPath row]];
    
    AsyncImageView *asyncImage = [[[AsyncImageView alloc] initWithFrame:CGRectMake(0, 10, 47, 43)] autorelease];
    asyncImage.tag = 999;
	NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], [dicField objectForKey:@"myUsername"]]];
	[asyncImage loadImageFromURL:avatarURL];
    [cell addSubview:asyncImage];
    
    UILabel *nameView =[[[UILabel alloc] initWithFrame:CGRectMake(55, 8, 200, 30)] autorelease];
    nameView.tag = 998;
    [nameView setBackgroundColor:[UIColor clearColor]];
    [nameView setFont:[UIFont boldSystemFontOfSize:16]];
    if (![[dicField objectForKey:@"myAlter"] isEqualToString:@""]) 
    {
        [nameView setText:[NSString stringWithFormat:@"%@ (%@)",[dicField objectForKey:@"myUsername"], [dicField objectForKey:@"myAlter"]]];
    }
    else 
    {
        [nameView setText:[dicField objectForKey:@"myUsername"]];
    }
    [cell addSubview:nameView];
    
    UILabel *locationView = [[[UILabel alloc] initWithFrame:CGRectMake(55, 27, 200, 30)] autorelease];
    locationView.tag = 997;
    [locationView setFont:[UIFont boldSystemFontOfSize:13]];
    [locationView setTextColor:[UIColor darkGrayColor]];
    [locationView setBackgroundColor:[UIColor clearColor]];
    [locationView setText:[dicField objectForKey:@"noticed"]];
    [cell addSubview:locationView];
    
    cell.textLabel.text = [dicField objectForKey:@"label"];
    [cell setBackgroundColor:[UIColor colorWithRed:((float) 235 / 255.0f) green:((float) 236 / 255.0f) blue:((float) 240 / 255.0f) alpha:0.45f]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sectionFields = [listOfSections objectAtIndex:[indexPath section]];
    NSDictionary *dicField = [sectionFields objectAtIndex:[indexPath row]];
    
    ContactDetail *contactDetail = [[ContactDetail alloc] init];
    NSString *fUsername = [[NSString alloc] initWithString:[dicField objectForKey:@"myUsername"]];
    contactDetail.friendUsername = fUsername;
    [fUsername release];
    [self.navigationController pushViewController:contactDetail animated:YES];
    [contactDetail release];
}

#pragma mark -
#pragma mark TabBar

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:[myTabBar.items objectAtIndex:1]];
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            break;
        case 2: 
            [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 3;
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
    [listOfSections removeAllObjects];
    [listOfSections addObject:[responseString JSONValue]];
    [myTableView reloadData];
    
    [responseString release];
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
